package com.csair.platform.cit.service.biz.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import com.csair.invoice.common.base.util.StringUtil;
import com.csair.invoice.common.base.util.collection.CollectionUtil;
import com.csair.invoice.common.base.vo.JsonResult;
import com.csair.platform.cit.facade.model.CitQueryParam;
import com.csair.platform.cit.facade.model.CitSendParam;
import com.csair.platform.cit.service.dao.CitDeclareRecordRepository;
import com.csair.platform.cit.service.entity.CitDeclareRecord;
import com.csair.platform.cit.service.feignclient.sbcenter.GdTaxUserClient;
import com.csair.platform.gts.sdk.CitInitDataClient;
import com.csair.platform.sbcenter.facade.model.login.GdTaxUserInfo;
import com.csair.platform.usercenter.facade.model.user.UserVo;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * [期初数据接口]服务实现类
 * @author ：caoyu
 * 
 */
@Slf4j
@Service
public class InitBaseServiceImpl {
    
    
	/**
	 * 企业所得税申报受理记录dao
	 */
	@Autowired
	protected CitDeclareRecordRepository declareRecordDao;
	
    /**
     * 广东电子税务局接口地址 
     */
    @Value("${dzswj.url}")
    private String serverUrl;
    
    /**
     * 广东电子税局用户信息接口
     */
    @Autowired
    private GdTaxUserClient gdTaxUserFeignClient;
    
    /**
     * 通过4.1接口获取期初数据
     * @return 期初数据返回报文
     */
    @SneakyThrows
    protected String getInitJsonData(CitQueryParam param, UserVo user) {
    	CitInitDataClient client = new CitInitDataClient(serverUrl);
    	//调申报中心，获取到税局用户信息
    	JsonResult<GdTaxUserInfo> userInfos = gdTaxUserFeignClient.getGdTaxUserByAccount(user.getAccount());
    	if (!userInfos.isSuccess()) {
    		throw new RuntimeException("请登录之后再操作!");
    	}
    	GdTaxUserInfo userInfo = userInfos.getData().get(0);
    	if (StringUtil.isEmpty(userInfo.getTaxNo())) {
    		throw new RuntimeException("请登录之后再操作!");
    	}
    	if (!userInfo.getTaxNo().equals(param.getNsrsbh())) {
    		throw new RuntimeException("当前用户授权访问的税号【" + userInfo.getTaxNo() + "】与访问的税号【" + param.getNsrsbh() + "】不一致!");
    	}
    	String ssoSessionId = userInfo.getSsoSessionId();
    	String nsrsbh = param.getNsrsbh();
    	String djxh = userInfo.getDjxh();
    	String sssqq = param.getSkssqq();
    	String sssqz = param.getSkssqz();
    	String jsonStr = client.getInitData(ssoSessionId, nsrsbh, djxh, sssqq, sssqz);
    	log.info("企业所得税季度申报期初数据查询返回报文：" + jsonStr);
    	return jsonStr;
    }
    
    /**
     * 获取调用接口需要相关请求参数
     * @param param 查询参数
     * @param user 当前用户
     * @return 调用接口需要相关请求参数nsrsbh=440101100017600格式
     */
    protected Map<String, String> getParams(CitQueryParam param, UserVo user) {
    	JsonResult<GdTaxUserInfo> userInfos = gdTaxUserFeignClient.getGdTaxUserByAccount(user.getAccount());
    	if (!userInfos.isSuccess()) {
    		throw new RuntimeException("请登录之后再操作!");
    	}
    	GdTaxUserInfo userInfo = userInfos.getData().get(0);
    	if (StringUtil.isEmpty(userInfo.getTaxNo())) {
    		throw new RuntimeException("请登录之后再操作!");
    	}
    	if (!userInfo.getTaxNo().equals(param.getNsrsbh())) {
    		throw new RuntimeException("当前用户授权访问的税号【" + userInfo.getTaxNo() + "】与访问的税号【" + param.getNsrsbh() + "】不一致!");
    	}
		Map<String, String> params = new HashMap<>();
		params.put("taxNo", param.getNsrsbh());
    	//该接口税号只能识别旧的15位，这里特殊处理
    	String nsrsbh = userInfo.getTaxNo().
    			replace("91440000100017600N", "440101100017600"). //股份
    			replace("91440000100005896P", "440101100005896"); //集团
		params.put("nsrsbh", nsrsbh);
		params.put("ssoSessionId", userInfo.getSsoSessionId());
		params.put("djxh", userInfo.getDjxh());
		params.put("skssqq", param.getSkssqq());
		params.put("skssqz", param.getSkssqz());
		params.put("zjlx", userInfo.getZjlx()); //操作用户证件类型    201-居民身份证
		params.put("zjhm", userInfo.getZjhm()); //操作用户证件号码
		params.put("yhm", userInfo.getYhm()); //操作用户名，形如： lxjtax
		params.put("xm", userInfo.getXm()); //操作用户姓名
		params.put("sjhm", "13000000000"); //操作用户手机号码
		params.put("zgswjgdm", userInfo.getGszgswjg()); //主管税务机关代码
		params.put("zgswjgmc", userInfo.getSwjgmc()); //主管税务机关名称
		
		return params;
    }
    
   
    
	/**
	 * 获取企业所得税申报受理记录
	 * @param param 申报参数
	 * @return 企业所得税申报受理记录
	 */
    protected CitDeclareRecord queryDeclareRecord(CitSendParam param) {
	    CitDeclareRecord query = new CitDeclareRecord();
	    query.setNsrsbh(param.getNsrsbh());
	    query.setSkssqq(param.getSkssqq());
	    query.setSkssqz(param.getSkssqz());
        Example<CitDeclareRecord> example = Example.of(query);
        List<CitDeclareRecord> declareRecords = declareRecordDao.findAll(example);
        if (CollectionUtil.isNotEmpty(declareRecords)) {
        	return declareRecords.get(0);
        }
        return null;
	}
    
    /**
     * 使用map去掉数据中的千分位
     * @param map
     * @return map去掉数据中的千分位
     */
    protected Map<String, Object> cleanThousandth(Map<String, Object> map) {
		for(Map.Entry<String, Object> entry : map.entrySet()){
            String mapValue = entry.getValue().toString();
            if (mapValue.contains(",")) {
            	entry.setValue(mapValue.replace(",", ""));
            }
        }
		return map;
    }

	/**
	 * 是否的包含 关键key
	 * @param key
	 * @return
	 */
	public boolean containsKey(String key){
		return "nsrsbh".equals(key) || "nsrmc".equals(key) || "id".equals(key) || "skssqq".equals(key) || "skssqz".equals(key) ;
	}

	/**
	 * 是否的包含 mxxh
	 * @param key
	 * @return
	 */
	public boolean containsMxxhKey(String key){
		return "mxxh".equals(key);
	}
}
